package com.th.therp.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.th.therp.context.BaseContext;
import com.th.therp.exception.BaseException;
import com.th.therp.mapper.PurchaseMapper;
import com.th.therp.pojo.dto.PurchaseDto;
import com.th.therp.pojo.dto.page.PurchasePageQueryDTO;
import com.th.therp.pojo.emtity.Inventory;
import com.th.therp.pojo.emtity.Purchase;
import com.th.therp.pojo.result.PageResult;
import com.th.therp.pojo.vo.PurchaseVo;
import com.th.therp.service.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Log4j2
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private MaterialBrandService materialBrandService;

    @Autowired
    private MaterialCategoryService materialCategoryService;

    public void add(PurchaseDto purchaseDto) {
        // 订单号:ORD+日期+UUID随机数(大写)
        String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String barcode = "PO" + datePrefix + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        // 获取线程局部变量的userId用于查找用户名
        Long userId = BaseContext.getCurrentId();
        String operator = userService.findNameById(userId);
        // 查找商品单价
        double purchasePrice = materialService.findPurchasePriceById(purchaseDto.getMaterial());
        double totalAmount = purchasePrice * purchaseDto.getQuantity();
        Purchase purchase = new Purchase();
        BeanUtils.copyProperties(purchaseDto,purchase);
        // 计算采购总金额
        purchase.setTotalAmount(totalAmount);
        purchase.setBarcode(barcode);
        purchase.setCreateTime(LocalDateTime.now());
        purchase.setOperator(operator);
        // 设置采购总金额
        purchaseMapper.add(purchase);
        // 向库存表新增商品库存数据(待完成)
        Integer categoryId = materialService.findMaterCategoryById(purchase.getMaterial());
        Integer brandId = materialService.findMaterialBrandById(purchase.getMaterial());
        String storeName = storeService.findNameById(purchase.getStore());
        String materialName = materialService.findMaterialNameById(purchase.getMaterial());
        String materialBarcode = materialService.findMaterialBarcodeById(purchase.getMaterial());
        String materialCategory = materialCategoryService.findCategoryNameById(categoryId);
        String materialBrand = materialBrandService.findBrandNameById(brandId);
        Inventory inventory = Inventory.builder()
                .storeId(purchase.getStore())
                .materialName(materialName)
                .materialBarcode(materialBarcode)
                .materialCategory(materialCategory)
                .materialBrand(materialBrand)
                .storeName(storeName)
                .quantity(purchase.getQuantity())
                .build();
        log.info("仓库添加数据:{}",inventory);
        // 查询指定仓库商品是否存在，不存在则添加
        Integer quantity = inventoryService.findQuantityByStoreIdAndBarcode(inventory.getStoreId(),materialBarcode);
        if (quantity == null){
            inventoryService.add(inventory);
        }else {
            // 如商品存在，则累加后修改
            inventory.setQuantity(quantity+purchase.getQuantity());
            inventoryService.updateQuantityByStoreIdAndBarcode(inventory);
        }
    }

    @Override
    public PageResult page(PurchasePageQueryDTO purchasePageQueryDTO) {
        PageHelper.startPage(purchasePageQueryDTO.getPageNum(),purchasePageQueryDTO.getPageSize());
        Page<Purchase> page = purchaseMapper.page(purchasePageQueryDTO);
        List<Purchase> purchaseList = page.getResult();
        List<PurchaseVo> purchaseVoList = new ArrayList<>();
        purchaseList.forEach(purchase -> {
            Integer storeId = purchase.getStore();
            Integer vendorId = purchase.getVendor();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH:mm:ss");
            String storeName = storeService.findNameById(storeId);
            String vendorName = vendorService.findNameById(vendorId);
            String materialName = materialService.findMaterialNameById(purchase.getMaterial());
            String materialBarcode = materialService.findMaterialBarcodeById(purchase.getMaterial());
            String createTime = purchase.getCreateTime().format(formatter);
            PurchaseVo purchaseVo = PurchaseVo.builder()
                    .id(purchase.getId())
                    .barcode(purchase.getBarcode())
                    .store(storeName)
                    .vendor(vendorName)
                    .materialName(materialName)
                    .materialBarcode(materialBarcode)
                    .totalAmount(purchase.getTotalAmount())
                    .quantity(purchase.getQuantity())
                    .operator(purchase.getOperator())
                    .createTime(createTime)
                    .build();
            purchaseVoList.add(purchaseVo);
        });
        return new PageResult(page.getTotal(),purchaseVoList);
    }

    // 根据时间范围查找采购订单的数量
    @Override
    public Integer findQuantityByTime(String startTime, String endTime) {
        Integer quantity = purchaseMapper.findQuantityByTime(startTime,endTime);
        if (quantity != null){
            return quantity;
        }else {
            return 0;
        }
    }

    // 根据时间范围查找采购订单的金额
    @Override
    public Double findTotalAmountByTime(String startTime, String endTime) {
        Double totalAmount = purchaseMapper.findTotalAmountByTime(startTime,endTime);
        if (totalAmount != null){
            return totalAmount;
        }else {
            return 0.0;
        }
    }

    //采购单退货
    @Override
    public void delete(Integer id) {
        //查找采购单商品编码
        Purchase purchase= purchaseMapper.findById(id);
        String materialBarcode = materialService.findMaterialBarcodeById(purchase.getMaterial());
        //查询存放仓库的商品数量
        Integer quantity = inventoryService.findQuantityByStoreIdAndBarcode(purchase.getStore(),materialBarcode);
        //如果仓库库存够退货，则退货并修改库存
        if (quantity != null){
            if (quantity > purchase.getQuantity()){
                purchaseMapper.delete(id);
                Integer updateQuantity = quantity - purchase.getQuantity();
                inventoryService.updateByStoreIdAndBarcode(purchase.getStore(),materialBarcode,updateQuantity);
            }else if (quantity < purchase.getQuantity()) {
                String store = storeService.findNameById(purchase.getStore());
                throw new BaseException(store + "：库存不足,无法退货");
            }
            else {
                //如果仓库库存与退货数量相等，则退货并删除库存
                Inventory inventory = new Inventory();
                inventory.setStoreId(purchase.getStore());
                inventory.setMaterialBarcode(materialBarcode);
                purchaseMapper.delete(id);
                inventoryService.deleteByStoreIdAndBarcode(inventory);
            }
        }else {
            String store = storeService.findNameById(purchase.getStore());
            throw new BaseException(store + "：库存不足,无法退货");
        }
    }
}